package com.kk.nb_order.exception;


import com.woniuxy.boot.common.pojo.ResultObj;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResultObj exceptionHandler(Exception e) {
        e.printStackTrace();
        if(e.getCause() instanceof OrderNotFoundException){
            return ResultObj.error().msg("订单不存在").code(503);
        }
        //违反数据库约束
        if (e instanceof DataIntegrityViolationException) {
            return ResultObj.error().msg(e.getMessage()).code(502);
        }
        //数据库异常，如连接出错，连接超时等
        else if (e instanceof DataAccessException) {
            return ResultObj.error().msg("数据库异常").code(504);
        }
        else if (e instanceof OrderNotFoundException) {
            return ResultObj.error().msg("订单不存在").code(503);
        }
        else if (e instanceof OrderStatusException) {
            return ResultObj.error().msg("订单状态异常").code(505);
        }
        //未知错误
        else {
            return ResultObj.error().msg("网络走丢了").code(599);
        }
    }


    @ExceptionHandler
    public ResultObj exceptionHandler(MethodArgumentNotValidException e) {
        HashMap<String, String> hashMap = new HashMap<>();
       e.getFieldErrors().forEach(fieldError -> hashMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
       return ResultObj.error().code(201).msg("校验错误").data(hashMap);
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultObj handleNotFoundException(NoHandlerFoundException e) {
        return ResultObj.error().msg("资源不见辣").code(404);
    }

}


